package com.bookkeeping.bookkeepingapi.service.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class JwtUtil {

    // JWT有效期(毫秒)
    private static final long EXPIRATION_TIME = 864000000; // 240小时=10天
//    private static final long EXPIRATION_TIME = 1000; // 240小时=10天
    private static final String JWT_TOKEN_KEY = "123321123321123321123321123321123321123321123321123321123321123321123321123321123321"; // 240小时=10天

    //获取token，颁发令牌
    public static String generateToken(String userId) {
        return Jwts.builder()
                .setSubject(userId)  // 设置主题
                .setIssuedAt(new Date())  // 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))  // 设置过期时间
                .signWith(SignatureAlgorithm.HS256, JWT_TOKEN_KEY)  // 使用密钥签名
                .compact();  // 生成JWT字符串
    }

    //解析token
    public static String parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(JWT_TOKEN_KEY)  // 设置签名密钥
                .build()
                .parseClaimsJws(token)  // 解析token
                .getBody()  // 获取负载
                .getSubject();  // 获取主题(用户名)
    }

    //获取用户传参中的令牌信息
    public static String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.isNotBlank(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
}
